<?php
require_once 'ResultItem.class.php';

class TableAdapter {
	
	private $table;
	private $conn;
	
	private $loggingPage, $delegatedEvents;
	
	private $isDebug;
	
	private $isSuccessfull;
	private $isInsert;
	private $isUpdate;
	
	private $disableEscape;
	
	public function getIsSuccessful() { return $this->isSuccessfull; }
	public function getIsInsert() { 	return $this->isInsert; }
	public function getIsUpdate() { 	return $this->isUpdate; }
	
	
	public function __construct($table=null) {
		if(isset($table)) { $this->setTable($table); }
		
		$this->conn = MySQLConnection::getInstance();
		
	}
	
	public function setTable($name) {
		$this->table = $name;
	}
	
	public function enableDebug() {
		$this->isDebug = true;
	}
	
	public function disableEscape() {
		$this->disableEscape = true;
	}
	
	public function setLoggingPage(Page $p) {
		$this->loggingPage = $p;
	}
	
	public function addEventDelegation($internalAction, $friendly, $file, $class, $function, $line) {
		$this->delegatedEvents[$internalAction] = array("friendly"=>$friendly, "file"=>$file, "class"=>$class, "function"=>$function, "line"=>$line);
	}
	
	public function getAllItems() {
		return ResultItem::getAllByQuery($this->table);		
	}

	public function getAllByQuery($sql, $args = null, $classType="ResultItem") {
		return ResultItem::getAllByQuery(str_replace("{table}", $this->table, $sql), $args, $classType);				
	}
	
	public function getSingleByQuery($sql, $args=null, $classType="ResultItem") {
		return ResultItem::getSingleByQuery(str_replace("{table}", $this->table, $sql), $args, $classType);
	}
		
	public function updateInsert($postValues, $pkField, $fieldPrefix="", $addKeyVal="") {
		
		//Find pkItem
		$pkName = ($fieldPrefix?$fieldPrefix."_":"").$pkField;
		
		if(!isset($postValues[$pkName]) && $pkField) {
			trigger_error("Primarykey '$pkName' not found in PostValues.");
			print_r($postValues);
			
		}
		else {
			
			if($this->isDebug) { echo "Primary key is: '$pkName'<br>\n"; }
			
			//Generate field, value pairs
			$set = array();
			while(list($key, $value)=each($postValues)) {
				if(substr($key, 0, strlen($fieldPrefix))==$fieldPrefix) {
					$field = substr($key, strlen($fieldPrefix)+($fieldPrefix?1:0));
					if($value) {
						$value = "'" . (!$this->disableEscape?mysql_escape_string($value):$value) . "'";
					}
					else {
						$value = "null";
					}
					$set = array_merge($set, array($field => $value));
				}
			}
			
			//Add Optional key, value pairs
			if(is_array($addKeyVal)) {
				$set = array_merge($set, $addKeyVal);
			}
			
			
			if(is_numeric($postValues[$pkName])) {

				$this->isUpdate = true;
				
				//Update Current
				$sql = "UPDATE $this->table SET ";
				while(list($field, $value)=each($set)) {
					
					//Only add, if not is Pk of Table
					if($field!=$pkField) {
						$sql.= $field . " = " . $value . ", ";
					}
					
				}
				
				$sql.= "changeUser = " . SecurityUser::getUser()->getPkSecurityUser() . ", changeDate=NOW()	WHERE $pkField = " . $set[$pkField];
			}
			else {
				
				$this->isInsert = true;
				
				//Insert new
				$sql = "INSERT INTO $this->table ";
				while(list($field, $value)=each($set)) {
					if($field!=$pkName) {
						$fields.= $field . ", ";
						$values.= "" . $value . ", ";
					}
				}
				$fields.="createUser, createDate";
				$values.="'".SecurityUser::getUser()->getPkSecurityUser()."', NOW()";
				
				$sql.="($fields) VALUES($values)";
			}
			
			if($this->isDebug) {
				echo $sql."<br>\n";
			}
			
			$this->conn->query($sql);
			$link = $this->conn->getLinkId();
			$lastID = mysql_insert_id($link);
			
			if($this->isDebug) { 
				echo "<br>Error-Number:</b> " .mysql_errno($link);
			}
			
			if(mysql_errno($link)==0) { 
				$this->isSuccessfull = true;
				if($this->isUpdate) {
					$event = $this->delegatedEvents["update"]; 
				}
				else {
					$event = $this->delegatedEvents["insert"];
				}
			}
			else {
				//Failed
				$event = $this->delegatedEvents["failed"];
			}
			
			
			if($event) {
				//Log Event if there is delegated one
				$this->loggingPage->logEvent($event["friendly"], $event["file"], $event["class"], $event["function"], $event["line"]);
			}
			
			$retval = ($this->isUpdate?mysql_affected_rows($link):$lastID);
			
			if($this->isDebug) {
				echo "<br>Return-Value is: '$retval'";
				//die();
			}
			
			return $retval;
			
		}
		
		return null;
	}
}
?>